package org.kukker.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import com.google.android.gdata.client.AndroidXmlParserFactory;
import com.google.android.gdata.client.JakartaGDataClient;
import com.google.wireless.gdata.calendar.client.CalendarClient;
import com.google.wireless.gdata.calendar.data.EventEntry;
import com.google.wireless.gdata.calendar.data.When;
import com.google.wireless.gdata.calendar.parser.xml.XmlCalendarGDataParserFactory;
import com.google.wireless.gdata.client.QueryParams;
import com.google.wireless.gdata.data.Feed;
import com.google.wireless.gdata.parser.GDataParser;

import org.kukker.DBHelper;
import org.kukker.R;
import org.kukker.R.id;
import org.kukker.R.layout;
import org.kukker.activity.BrowseSavedEventsActivity.UserActivity;
import org.kukker.app.KukkerApp;
import org.kukker.dialog.AboutDialog;
import org.kukker.dialog.PreferenceDialog;
import org.kukker.event.Event;
import org.kukker.event.EventSearchParameters;
import org.kukker.event.IEventSearchListener;
import org.kukker.list.IKukkerListItemListener;
import org.kukker.list.IKukkerListItemView;
import org.kukker.list.KukkerListAdapter;
import org.kukker.list.KukkerListItemView;
import org.kukker.list.KukkerListView;

import org.kukker.upcoming.UpcomingEvent;
import org.kukker.upcoming.UpcomingWebService;
import org.kukker.view.EventDetailView;
import org.kukker.view.ISearchEventsInputListener;
import org.kukker.view.SearchEventsInput;
import org.kukker.view.EventDetailView.IEventDetailViewListener;

import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.Menu.Item;
import android.view.View.OnClickListener;
import android.view.View.OnPopulateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsoluteLayout;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.ContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.xml.dom.DocumentImpl;
import android.xml.dom.ElementImpl;

public class SearchEventsActivity extends ListActivity {

	enum UserActivity {
		VIEW_EVENTDETAILS, VIEW_EVENTSEARCHRESULTS;
	}

	/*
	 * enum EventItemContextMenuOptions { SAVE_EVENT (0,0), FORWARD_EVENT (0,0),
	 * SHOW_DETAILS(0,0), CANCEL (0,0);
	 * 
	 * public int group; public int id;
	 * 
	 * private EventItemContextMenuOptions(int group,int id){ this.group =
	 * group; this.id = id; } }
	 */
	private boolean showDebugMessage = false;
	private Handler mHandler;

	// context menu options
	private static final int CMO_EVENT_SAVETOLOCAL = 0;
	private static final int CMO_EVENT_SHOWDETAILS = 4;
	private static final int CMO_EVENT_REMOVEFROMLOCAL = 1;
	private static final int CMO_EVENT_FORWARD = 2;
	private static final int CMO_EVENT_CANCEL = 3;
	private static final int CMO_SEARCH = 10;

	private static final int CMO_EVENTDETAILS_BACKTORESULT = 1;
	private static final int CMO_EVENTDETAILS_GETLOCATIONMAP = 2;
	private static final int CMO_EVENTDETAILS_SENDTOFRIENDS = 3;
	private static final int CMO_EVENTDETAILS_SAVETOLOCAL = 4;
	private static final int CMO_EVENTDETAILS_CANCEL = 5;

	// hack
	// TODO re-architect this from db.
	private static final int ORIGIN_ID_LOCAL = 0;
	private static final int ORIGIN_ID_UPCOMING = 1;

	private UserActivity mUserActivity = UserActivity.VIEW_EVENTDETAILS;

	private KukkerListView eventListView;
	private KukkerListAdapter eventListAdapter;
	private EventDetailView eventDetailView;
	private SearchEventsInput eventSearchInput;

	private View eventLayout;

	UpcomingWebService uws;
	private DBHelper dbHelper;
	private String debugtag0 = "Kukker.java";

	private EventSearchParameters mEventSearchParams;

	// containers
	private View eventsSearchResultContainer;
	private View eventsSearchInputContainer;
	private Event event0;

	// dialog
	private Dialog mDialogSearch;
	private Dialog mDialogPreferences;
	private Dialog mDialogAbout;

	// listeners
	IEventDetailViewListener mEventDetailViewListener;
	IKukkerListItemListener mKukkerListItemListener;
	IEventSearchListener mEventSearchUpcomingListener;
	OnPopulateContextMenuListener mEventListViewOnPopulateContextMenuListener;
	OnPopulateContextMenuListener mEventDetailsOnPopulateContextMenuListener;

	private int screenWidth;
	private int screenHeight;

	SearchEventsRunnable ser = new SearchEventsRunnable();

	private void setSearchParameters(EventSearchParameters esp) {
		this.mEventSearchParams = esp;

	}

	private ISearchEventsInputListener mSearchEventsInputListener;

	private void initDialogs(){
		this.initDialogSearch();
		this.initDialogPreferences();
		this.initDialogAbout();
	}
	
	private void initDialogAbout(){
		mDialogAbout = new AboutDialog(this);				
	}
	
	private void initDialogPreferences(){
		this.mDialogPreferences = new PreferenceDialog(this);		
	}	
	
	private void initDialogSearch() {
		// Dialog
		mDialogSearch = new Dialog(SearchEventsActivity.this);
		mDialogSearch.setContentView(R.layout.dialog_searchevent);
		mDialogSearch.setTitle("Search public events");
		Button searchButton = (Button) mDialogSearch
				.findViewById(R.id.eventsearchinput_button_search);
		Button returnButton = (Button) mDialogSearch
				.findViewById(R.id.eventsearchinput_button_return);

		searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				SearchEventsInput esi = (SearchEventsInput) mDialogSearch
						.findViewById(R.id.eventsearchinput_searcheventsinput);
				Properties searchParams = esi.getSearchParameters();

				ser = new SearchEventsRunnable();
				ser.setSearchParameters(searchParams);

				Handler handler = KukkerApp.mUpcomingLocalService.mServiceHandler;
				handler.post(ser);

				eventListView.requestFocus();
				mDialogSearch.dismiss();
			}
		});

		returnButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				mDialogSearch.dismiss();
			}
		});
	}

	private void initListeners() {
		this.mSearchEventsInputListener = new ISearchEventsInputListener() {
			public void OnSearchClicked(final Properties params) {
				// eventSearchInput.setDetectIncomingEvents(false);
				// findViewById(R.id.eventsearchinput_container).setVisibility(View.GONE);
				// eventSearchInput.setVisibility(View.GONE);
				// eventListView.setDetectIncomingEvents(true);

				ser = new SearchEventsRunnable();
				ser.setSearchParameters(params);

				Handler handler = KukkerApp.mUpcomingLocalService.mServiceHandler;
				handler.post(ser);

				// Log.i("debug", "doAnim4");
				doAnim4();
			}
		};

		this.mEventSearchUpcomingListener = new IEventSearchListener() {
			public void onEventFound(Event event) {
				// Log.i("db","onEventFound, name:"+event.name);
				Event savedRecord = dbHelper
						.fecthEventUsingRemoteId(event.remoteId);
				if (savedRecord != null) {
					// Log.i("db","saved found id:"+event.remoteId);
					event.setIsSaved(true);
				} else {
					// Log.i("db","not found in local db, id:"+event.remoteId);
				}
			}
		};

		this.mEventDetailViewListener = new IEventDetailViewListener() {

			@Override
			public void onKeyRightUp() {
				/*
				 * Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +
				 * 
				 * "[" +
				 * 
				 * "]"
				 *  + "[" + "onKeyRightUp"
				 *  + "]"); // go back to search results
				 */
			}

			@Override
			public void onClick() {

				// go back to events list

				// mUserActivity = mUserActivity.VIEW_EVENTSEARCHRESULTS;
				// doAnim2();
			}

			@Override
			public void onClickDCenter() {
				// TODO Auto-generated method stub
				mUserActivity = UserActivity.VIEW_EVENTSEARCHRESULTS;
				doAnim2();
			}

		};

		this.mKukkerListItemListener = new IKukkerListItemListener() {

			@Override
			public void onListItemKeyLeftDown(IKukkerListItemView view) {

				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyLeftDown "

				+ "]");

			}

			@Override
			public void onListItemKeyLeftUp(IKukkerListItemView view) {
				// TODO Auto-generated method stub

				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyLeftUp"

				+ "]");

			}

			@Override
			public void onListItemKeyRightDown(IKukkerListItemView view) {
			}

			@Override
			public void onListItemKeyRightUp(IKukkerListItemView view) {
				/*
				 * Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +
				 * "[" + "]" + "[" + "onListItemKeyRightUp" + "]");
				 */

				// eventListView.setDetectIncomingEvents(false);
				// doAnim3();
				// dbHelper.deleteEventUsingRemoteId(data.remoteId);
				// dbHep
			}

			@Override
			public void onListItemKeyLeftClick(IKukkerListItemView view) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onListItemKeyDCenterClick(IKukkerListItemView view) {
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyDCenterClick"

				+ "]");

				event0 = view.getData();

				eventListView.storeLastSelectedItem();
				eventListView.setActivated(false);

				doAnim1();
			}

			@Override
			public void onListItemKeyMenuClick(IKukkerListItemView view) {
				// TODO Auto-generated method stub
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyMenuClick"

				+ "]");

				// View aView = eventListView.getSelectedView();
				// if(aView != null){
				// int loc[] = new int[2];
				// aView.getAbsoluteLocationOnScreen(loc);

			}

		};

		this.mEventListViewOnPopulateContextMenuListener = new OnPopulateContextMenuListener() {
			public void onPopulateContextMenu(ContextMenu contextmenu,
					View view, Object obj) {

				// Log.i("contextmenu","populate");

				KukkerListView lv = (KukkerListView) view;
				int pos = lv.getLastPressedDownItemPosition();
				UpcomingEvent data = (UpcomingEvent) lv.getAdapter().getItem(
						pos);

				// create menu items
				Item showDetailsMenuItem = contextmenu.add(0,
						CMO_EVENT_SHOWDETAILS, "Show Details");
				Item saveMenuItem = contextmenu.add(0, CMO_EVENT_SAVETOLOCAL,
						"Save to device");
				Item forwardMenuItem = contextmenu.add(0, CMO_EVENT_FORWARD,
						"Send to friends");
				Item removeFromLocalMenuItem = contextmenu.add(0,
						CMO_EVENT_REMOVEFROMLOCAL, "Remove from device");
				Item cancelMenuItem = contextmenu.add(0, CMO_EVENT_CANCEL,
						"Cancel");

				// hide or show menu items based on data.
				boolean isSavedToLocal = data.getIsSaved();
				if (isSavedToLocal) {
					saveMenuItem.setShown(false);
					removeFromLocalMenuItem.setShown(true);
				} else {
					saveMenuItem.setShown(true);
					removeFromLocalMenuItem.setShown(false);
				}
				//

				// obj = view;

			}
		};

		this.mEventDetailsOnPopulateContextMenuListener = new OnPopulateContextMenuListener() {
			public void onPopulateContextMenu(ContextMenu contextmenu,
					View view, Object obj) {

				Log
						.i("contextmenu",
								"populating context menu for eventdetails");

				KukkerListView lv = (KukkerListView) view;
				int pos = lv.getLastPressedDownItemPosition();
				UpcomingEvent data = (UpcomingEvent) lv.getAdapter().getItem(
						pos);

				// create menu items
				Item showDetailsMenuItem = contextmenu.add(0,
						CMO_EVENTDETAILS_BACKTORESULT, "Go back to results");
				Item saveMenuItem = contextmenu.add(0,
						CMO_EVENTDETAILS_SAVETOLOCAL, "Save");
				Item forwardMenuItem = contextmenu.add(0,
						CMO_EVENTDETAILS_SENDTOFRIENDS, "Forward to a friend");
				Item cancelMenuItem = contextmenu.add(0,
						CMO_EVENTDETAILS_CANCEL, "Cancel");

				// hide or show menu items based on data.
				/*
				 * boolean isSavedToLocal = data.getIsSaved(); if
				 * (isSavedToLocal) { saveMenuItem.setShown(false);
				 * removeFromLocalMenuItem.setShown(true); } else {
				 * saveMenuItem.setShown(true);
				 * removeFromLocalMenuItem.setShown(false); } //
				 */
			}
		};

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// KukkerApp.createOptionsMenu(menu);

		// Log.i("optionsmenu",this.getClass().getName()+",
		// onCreateOptionsMenu");
		menu.setQwertyMode(false);

		SubMenu subMenu1 = menu.addSubMenu(0, 0, "Event",
				KukkerApp.Icons.OPTIONS_EVENT);
		subMenu1.setDefaultItem(KukkerApp.OptionsMenu.OMO_SHOWDETAILS);

		Item mi_showdetails = subMenu1.add(0,
				KukkerApp.OptionsMenu.OMO_SHOWDETAILS, "Show event details",
				KukkerApp.Icons.OPTIONS_EVENT_SHOWDETAILS);
		mi_showdetails.setNumericShortcut('1');

		Item mi_addtolocal = subMenu1.add(0,
				KukkerApp.OptionsMenu.OMO_SAVETOLOCAL, "Save event",
				KukkerApp.Icons.OPTIONS_EVENT_SAVE);
		mi_addtolocal.setNumericShortcut('2');

		Item mi_new = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_CREATEEVENT,
				"Create new ", KukkerApp.Icons.OPTIONS_EVENT_CREATENEW);
		mi_new.setNumericShortcut('3');

		Item mi_forward = subMenu1.add(0,
				KukkerApp.OptionsMenu.OMO_SENDTOFRIENDS, "Send to a friend",
				KukkerApp.Icons.OPTIONS_EVENT_SENDTOFRIENDS);
		mi_forward.setNumericShortcut('4');

		Item mi_remove = subMenu1.add(0,
				KukkerApp.OptionsMenu.OMO_DELETEFROMLOCAL, "Delete",
				KukkerApp.Icons.OPTIONS_EVENT_DELETE);
		mi_remove.setNumericShortcut('0');

		//

		SubMenu subMenu2 = menu.addSubMenu(0, 0, "Search",
				KukkerApp.Icons.OPTIONS_SEARCH);
		subMenu2.add(0, KukkerApp.OptionsMenu.OMO_SEARCH, "New Search",
				KukkerApp.Icons.OPTIONS_SEARCH_PUBLIC);
		subMenu2.add(0, KukkerApp.OptionsMenu.OMO_SEARCH_PAUSE, "Pause",
				KukkerApp.Icons.OPTIONS_SEARCH_PAUSE);
		subMenu2.add(0, KukkerApp.OptionsMenu.OMO_SEARCH_RESUME, "Resume",
				KukkerApp.Icons.OPTIONS_SEARCH_START);

		//

		SubMenu subMenu3 = menu.addSubMenu(0, 0, "Help",
				KukkerApp.Icons.OPTIONS_HELP);
		subMenu3.add(0, KukkerApp.OptionsMenu.OMO_ABOUT, "About", KukkerApp.Icons.OPTIONS_HELP_ABOUT);
		subMenu3.add(0, 0, "Tips", KukkerApp.Icons.OPTIONS_HELP_TIPS);

		//

		SubMenu subMenu4 = menu.addSubMenu(0, 0, "Options",
				KukkerApp.Icons.OPTIONS_OPTIONS);
		subMenu4.add(0, 0, "Preferences", KukkerApp.Icons.OPTIONS_PREFERENCES);

		return true;

	}

	public void onDestroy() {
		super.onDestroy();
		ser.stop();
		if (showDebugMessage) {
			Log
					.i("activity_process", this.getClass().getName()
							+ " onDestroy ");
		}
		this.dbHelper.close();
	}

	public void onFreeze(Bundle icicle) {
		super.onFreeze(icicle);
		if (showDebugMessage) {
			Log.i("activity_process", this.getClass().getName() + " onFreeze ");
		}
	}

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		this.setTitle("Search results");

		boolean granted = requestWindowFeature(Window.FEATURE_PROGRESS);
		setProgressBarVisibility(false);

		setContentView(R.layout.upcoming_events_list);

		this.mHandler = new Handler();

		// Retrieve screen configs
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		this.screenHeight = dm.heightPixels;
		this.screenWidth = dm.widthPixels;

		// Initialize
		this.initAnimations();
		this.initListeners();
		this.initDialogs();
		dbHelper = new DBHelper(this);

		// setup webservice
		uws = new UpcomingWebService();
		uws.setOnEventFoundListener(this.mEventSearchUpcomingListener);
		uws.perPage = 100;
		uws.page = 1;
		//

		// Log.i("DEBUG","granted:"+granted);

		// obtain views
		this.eventDetailView = (EventDetailView) findViewById(R.id.kukkerevent_eventdetail);
		this.eventsSearchResultContainer = findViewById(R.id.events_search_result_container);
		this.eventLayout = findViewById(R.id.events_eventlayout);
		this.eventSearchInput = (SearchEventsInput) findViewById(R.id.eventsearchinput_searcheventsinput);
		this.eventsSearchInputContainer = findViewById(R.id.eventsearchinput_container);
		this.eventListView = (KukkerListView) getListView();
		this.eventListView.setEmptyView(findViewById(R.id.empty));
		//	 

		// set up adapters
		eventListAdapter = new KukkerListAdapter(this);
		// eventListAdapter.setListItemOnPopulateContextMenuListener(this.mOnPopulateContextMenuListener);
		eventListAdapter.setListView(eventListView);
		eventListView.setAdapter(eventListAdapter);

		// wire up events
		eventDetailView.setListener(this.mEventDetailViewListener);
		eventListView.setKukkerListItemListener(this.mKukkerListItemListener);
		// eventListView.setOnItemClickListener(KukkerListView.getDefaultOnItemClickListener());
		eventSearchInput
				.setSearchEventsInputListener(this.mSearchEventsInputListener);

		// context menu
		eventListView
				.setOnPopulateContextMenuListener(this.mEventListViewOnPopulateContextMenuListener);
		eventDetailView
				.setOnPopulateContextMenuListener(this.mEventDetailsOnPopulateContextMenuListener);

		/*
		 * setProgressBarVisibility(true); setProgress(5000);
		 * setProgressBarIndeterminate(false); setProgressBarVisibility(true);
		 */

		/*
		 * Properties esp = new Properties(); esp.put("location", "vancouver");
		 * esp.put("searchTerm", ""); updateResultsList(esp);
		 */

		// initial focus and events detection configuration.
		eventListView.setDetectIncomingEvents(true);
		eventDetailView.setDetectIncomingEvents(false);
		// eventSearchInput.setDetectIncomingEvents(true);
		eventSearchInput.setVisibility(View.GONE);

		this.mDialogSearch.show();
	}

	/*
	 * private synchronized void updateResultsList(Properties params) { Event
	 * events[] = this.invokeSearch(params); Log.i("Upcoming", "Num events:" +
	 * events.length); }
	 */

	private View subView1;

	// private int subView1_id = 2;

	private void createSubViews() {
		subView1 = new LinearLayout(this);
		subView1.setBackgroundColor(Color.RED);
		TextView tv = new TextView(this);
		tv.setText("HelloWorld");
		tv.setTextColor(Color.WHITE);
		tv.setTextSize(20);

		Button btn = new Button(this);
		btn.setText("Button");

		btn.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		((ViewGroup) subView1).addView(btn);

		tv.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		((ViewGroup) subView1).addView(tv);

		subView1.setLayoutParams(new AbsoluteLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1, 1));

		// findViewById(id);
		FrameLayout fl = (FrameLayout) this
				.findViewById(R.id.events_list_framelayout_0);
		fl.addView(subView1);
	}

	/*
	 * protected void onListItemClick(ListView l, View v, int position, long id) {
	 * //Log.i("DEBUG", "onListItemCLick:" + position); //Adapter adapter =
	 * this.getListView().getAdapter();
	 * //this.getListView().setOnItemClickListener((OnItemClickListener) this); //
	 * ((EventListAdapter)adapter).toggle(position); }
	 */

	/*
	 * protected Event[] invokeSearch(Properties params) { // String apiKey =
	 * "6efc1a7606"; uws.setMethod(UpcomingWebService.Method.EVENT_SEARCH);
	 * uws.setParameters(params); //Log.i("webservice",
	 * params.getProperty("location")); Event[] events = uws.get();
	 * 
	 * return events;
	 *  }
	 */

	private DocumentImpl getMockData() {

		DocumentBuilderFactory dbf1 = DocumentBuilderFactory.newInstance();

		dbf1.setValidating(false);
		dbf1.setExpandEntityReferences(true);
		dbf1.setIgnoringComments(true);
		dbf1.setNamespaceAware(false);

		DocumentBuilder db;
		// XmlPullParser xmlpullparser =
		// this.getResources().getXml(R.xml.eventsearch);
		// xmlpullparser.

		try {
			db = dbf1.newDocumentBuilder();
			// InputSource inputSource = new InputSource();
			// StringReader stringReader = new StringReader();
			File xmlfile0 = new File("/data/data/org.kukker", "eventsearch.xml");

			DocumentImpl doc = (DocumentImpl) db.parse(xmlfile0);

			return doc;
		} catch (ParserConfigurationException e) {
			Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// / CONTEXT MENU HANDLING

	public boolean onOptionsItemSelected(Item item) {
		super.onOptionsItemSelected(item);
		int pos;

		pos = eventListView.getSelectedItemPosition();

		KukkerListItemView view = (KukkerListItemView) eventListView
				.getSelectedView();
		Event data = (Event) eventListView.getAdapter().getItem(pos);
		// Log.i("debug","selected selected pos:"+pos);
		// Log.i("debug","selected view:"+
		// ((view!=null)?view.getClass().getName():"class null"));

		switch (item.getId()) {
		case KukkerApp.OptionsMenu.OMO_CREATEEVENT:
			this.startSubActivity(new Intent(SearchEventsActivity.this,
					CreateNewEventActivity.class),
					KukkerApp.ACTIVITY_EVENTCREATE);
			break;
		case KukkerApp.OptionsMenu.OMO_SEARCHPUBLICEVENTS:
			this
					.startSubActivity(new Intent(SearchEventsActivity.this,
							SearchEventsActivity.class),
							KukkerApp.ACTIVITY_EVENTSEARCH);
			break;
		case KukkerApp.OptionsMenu.OMO_SHOWDETAILS:
			showEventDetails(data, pos, view);
			break;
		case KukkerApp.OptionsMenu.OMO_SAVETOLOCAL:
			if (view != null && data != null) {
				saveEvent(data, view);
			}
			break;
		case KukkerApp.OptionsMenu.OMO_SEARCH:
			this.mDialogSearch.show();
			break;
		case KukkerApp.OptionsMenu.OMO_SEARCH_PAUSE:
			this.ser.pause();
			break;
		case KukkerApp.OptionsMenu.OMO_SEARCH_RESUME:
			this.ser.resume();
			break;
		case KukkerApp.OptionsMenu.OMO_ABOUT:
			this.mDialogAbout.show();
			break;	
		default:
			break;
		}
		return true;
	}

	private void showEventDetails(Event data, int lastSelectedPosition,
			KukkerListItemView itemView) {
		mUserActivity = UserActivity.VIEW_EVENTDETAILS;
		eventListView.setLastSelectedItemPosition(lastSelectedPosition);
		eventListView.setLastSelectedItem(itemView);
		event0 = data;
		// eventListView.setActivated(false); //IMPORTANT
		if (itemView == null) {
			if (showDebugMessage) {
				Log.i("agus", "itemView is null");
			}
		}
		if (showDebugMessage) {
			Log.i("agus", "last selected position :" + lastSelectedPosition);
		}

		doAnim1();
	}

	// / CONTEXT MENU HANDLING

	public boolean onContextItemSelected(Item item) {
		super.onContextItemSelected(item);

		ContextMenuInfo menuInfo = (ContextMenuInfo) item.getMenuInfo();
		if (showDebugMessage) {
			Log.i("contextmenu", "menuinfo: " + menuInfo.getClass().getName());
		}
		KukkerListItemView itemView = (KukkerListItemView) menuInfo.targetView;

		// Object obj = view.getListView();
		// Log.i("debug","onContextItemSelected: view:" +
		// view.getClass().getSimpleName());
		// Log.i("debug","onContextItemSelected: view.getListView:" +
		// obj.getClass().getSimpleName());

		Event data = null;
		int lastSelectedPosition = 0;

		if (itemView != null) {
			KukkerListView listView = itemView.getListView();
			// Log.i("debug","LISTVIEW:"+listView.toString());
			lastSelectedPosition = listView.getLastPressedDownItemPosition(); // use
																				// hack
			data = (Event) eventListView.getAdapter()
					.getItem(menuInfo.position);

		}

		switch (item.getId()) {
		case CMO_EVENT_CANCEL:
			break;
		case CMO_EVENT_SAVETOLOCAL:
			if (data != null) {
				saveEvent(data, itemView);
			}
			break;

		case CMO_EVENT_FORWARD:
			break;

		case CMO_EVENT_SHOWDETAILS:
			mUserActivity = UserActivity.VIEW_EVENTDETAILS;
			eventListView.setLastSelectedItemPosition(lastSelectedPosition);
			eventListView.setLastSelectedItem(itemView);
			event0 = data;
			doAnim1();
			break;

		case CMO_EVENT_REMOVEFROMLOCAL:
			if (data != null) {
				this.removeEvent(data, itemView);
			}
			break;
		}
		return true;
	}

	/**
	 * Removes event from phone
	 * 
	 * @param data
	 * @param view
	 */
	private void removeEvent(Event data, KukkerListItemView view) {
		if (data == null) {
			return;
		}
		this.dbHelper.deleteEventUsingRemoteId(data.remoteId);
		data.setIsSaved(false);
		view.updateView();
	}

	/**
	 * Saves event to phone
	 * 
	 * @param data
	 * @param view
	 */
	private void saveEvent(Event data, KukkerListItemView view) {
		// Event data = (Event) eventListView.getSelectedItem();
		// KukkerListItemView view = (KukkerListItemView)
		// eventListView.getSelectedView();

		// check if selected data has been saved to local

		if (data == null) {
			Log.i("debug", "no data found");
			// return -1;
		}

		boolean hasBeenSaved = data.getIsSaved();

		if (!hasBeenSaved) {
			// save it to local

			// Object data =
			// eventListAdapter.getItem(listItemView.getPosition());

			if (showDebugMessage) {
				Log.i("save0", this.getClass().getName()
						+ ", saveEvent(), remoteId: "
						+ ((UpcomingEvent) data).remoteId + "");
			}

			// TODO: impl saving branching based on data type
			// saveEvent((UpcomingEvent) data);
			data.originId = 1;
			long newRowId = this.dbHelper.insertEvent(data, ORIGIN_ID_UPCOMING);

			if (newRowId != -1) {
				// set a flag
				data.setIsSaved(true);

				// redisplay view
				view.updateView();
			}

		} else {
			// delete local data

			int remoteId = ((UpcomingEvent) data).remoteId;
			dbHelper.deleteEventUsingRemoteId(remoteId);
			data.setIsSaved(false);
			view.updateView();

		}

	}

	// / animation

	int sw = 319;

	TranslateAnimation animation_searchresults_show;
	TranslateAnimation animation_searchresults_hide;
	AnimationListener animationListener_searchresults_show;
	AnimationListener animationListener_searchresults_hide;
	boolean isStarted_animation_searchResults_show = false;
	boolean isStarted_animation_searchResults_hide = false;

	TranslateAnimation animation_eventsearchinput_show;
	TranslateAnimation animation_eventsearchinput_hide;
	AnimationListener animationListener_eventsearchinput_show;
	AnimationListener animationListener_eventsearchinput_hide;
	boolean isStarted_animation_searchinput_show = false;
	boolean isStarted_animation_searchinput_hide = false;

	private void initAnimations() {

		this.animation_searchresults_show = new TranslateAnimation(0,
				-this.screenWidth, 0, 0);
		this.animation_searchresults_hide = new TranslateAnimation(0,
				this.screenWidth, 0, 0);

		this.animation_eventsearchinput_show = new TranslateAnimation(0, 0, 0,
				this.screenHeight);
		this.animation_eventsearchinput_hide = new TranslateAnimation(0, 0, 0,
				-this.screenHeight);

		this.initAnimationListeners();

		this.init_anim_searchresults();
		this.init_anim_searchinput();

		// eventsSearchResultContainer.setDrawingCacheEnabled(true);
		// eventsSearchResultContainer.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
	}

	private void init_anim_searchresults() {
		animation_searchresults_show
				.setAnimationListener(animationListener_searchresults_show);
		animation_searchresults_show.setStartOffset(300);
		animation_searchresults_show.setDuration(800);

		animation_searchresults_hide
				.setAnimationListener(animationListener_searchresults_hide);
		animation_searchresults_hide.setStartOffset(300);
		animation_searchresults_hide.setDuration(800);
	}

	private void init_anim_searchinput() {
		animation_eventsearchinput_show
				.setAnimationListener(animationListener_eventsearchinput_show);
		animation_eventsearchinput_show.setStartOffset(300);
		animation_eventsearchinput_show.setDuration(1000);

		animation_eventsearchinput_hide
				.setAnimationListener(animationListener_eventsearchinput_hide);
		animation_eventsearchinput_hide.setStartOffset(300);
		animation_eventsearchinput_hide.setDuration(1000);
	}

	private void initAnimationListeners() {

		// hide event details, show search results
		this.animationListener_searchresults_show = new AnimationListener() {
			public void onAnimationEnd() {
				if (showDebugMessage) {
					Log.i("debug", "end anim");
				}
				LayoutParams lp = eventsSearchResultContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.x = 0;

				//
				eventsSearchResultContainer.setLayoutParams(allp);

				eventDetailView.setDetectIncomingEvents(false);
				eventListView.setDetectIncomingEvents(true);

				// eventListView.setBlockChildEvents(false);
				eventListView.setFocusableInTouchMode(true);

				// eventLayout.requestFocus();
				// animation_searchResults_show.reset();

				isStarted_animation_searchResults_show = false;
				eventsSearchResultContainer.clearAnimation();

			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				// eventDetailView.setDetectIncomingEvents(false);
				// eventListView.setDetectIncomingEvents(true);
				Log.i("debug", "start anim");
				// eventDetailView.setVisibility(View.GONE);

			}
		};

		/**
		 * show event details
		 */
		this.animationListener_searchresults_hide = new AnimationListener() {
			public void onAnimationEnd() {
				Log.i("debug", "end anim");

				LayoutParams lp = eventsSearchResultContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.x = screenWidth - 1;

				eventsSearchResultContainer.setLayoutParams(allp);
				eventDetailView.requestFocus();

				isStarted_animation_searchResults_hide = false;
				eventsSearchResultContainer.clearAnimation();
			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				Log.i("debug", "start anim");
				eventDetailView
						.populateEventDetailsView((UpcomingEvent) event0);
				eventListView.setDetectIncomingEvents(false);
				eventDetailView.setDetectIncomingEvents(true);
				eventDetailView.scrollTo(0, 0);
				// eventListView.setActivated(false);
				// eventListView.storeLastSelectedItem();

			}
		};

		// //////

		// show searchinput
		this.animationListener_eventsearchinput_show = new AnimationListener() {
			public void onAnimationEnd() {
				LayoutParams lp = eventsSearchInputContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.y = 0;
				eventsSearchInputContainer.setLayoutParams(allp);

				eventSearchInput.requestFocus();

				eventsSearchInputContainer.clearAnimation();
				isStarted_animation_searchinput_show = false;
			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				eventListView.setDetectIncomingEvents(false);
				eventSearchInput.setDetectIncomingEvents(true);
			}
		};

		/**
		 * hide search input hide event search input ---- to show ---> hidden
		 * search results list
		 */
		this.animationListener_eventsearchinput_hide = new AnimationListener() {
			public void onAnimationEnd() {
				Log.i("debug", "anim list, onAnimEnd");
				LayoutParams lp = eventsSearchInputContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.y = -screenHeight;
				eventsSearchInputContainer.setLayoutParams(allp);

				// eventSearchInput.setDetectIncomingEvents(false);
				eventListView.setDetectIncomingEvents(true);
				// eventListView.setBlockChildEvents(false);

				isStarted_animation_searchinput_hide = false;
				eventsSearchInputContainer.clearAnimation();

			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				Log.i("debug", "anim list, onAnimStart, h:" + screenHeight);
				// eventListView.setDetectIncomingEvents(true);
				eventSearchInput.setDetectIncomingEvents(false);
				// eventDetailView.scrollTo(0,0);
			}
		};
	}

	// hide search results
	private void doAnim1() {
		if (!isStarted_animation_searchResults_hide
				&& !isStarted_animation_searchResults_show) {
			Log.i("debug", "doAnim1");
			// eventsSearchResultContainer.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
			eventsSearchResultContainer
					.startAnimation(animation_searchresults_hide);
			isStarted_animation_searchResults_hide = true;
		} else {

		}
	}

	// show search results
	private void doAnim2() {
		if (!isStarted_animation_searchResults_show
				&& !isStarted_animation_searchResults_hide) {
			Log.i("debug", "doAnim2");
			eventsSearchResultContainer
					.startAnimation(animation_searchresults_show);
			isStarted_animation_searchResults_show = true;
		} else {

		}
	}

	/**
	 * Show event search input
	 */
	private void doAnim3() {

		if (!isStarted_animation_searchinput_show) {
			eventListView.storeLastSelectedItem();
			// eventListView.setActivated(false);

			eventsSearchInputContainer
					.startAnimation(animation_eventsearchinput_show);
			isStarted_animation_searchinput_show = true;
		} else {

		}

	}

	/**
	 * Hide event search input
	 */
	private void doAnim4() {

		if (!isStarted_animation_searchinput_hide) {
			// Log.i("debug", "inside doanim4");
			eventsSearchInputContainer
					.startAnimation(animation_eventsearchinput_hide);
			isStarted_animation_searchinput_hide = true;
		} else {

		}
	}

	class SearchEventsRunnable implements Runnable {

		Properties searchParams;
		int totalFound = 0;
		boolean isPaused = false;

		public void setSearchParameters(Properties params) {
			this.searchParams = params;
		}

		private boolean isRunning = false;

		public synchronized void stop() {
			runOnUIThread(updateProgress);
			this.isRunning = false;
		}

		public synchronized void pause() {
			this.isPaused = true;
			if (isRunning) {
				runOnUIThread(new Runnable() {
					public void run() {
						setTitle("search paused - found so far: " + totalFound);
						setProgressBarVisibility(false);
					}
				});
			}
		}

		public synchronized void resume() {
			this.isPaused = false;
			if (isRunning) {
				runOnUIThread(new Runnable() {
					public void run() {
						setTitle("search resumed - found so far: " + totalFound);
						setProgressBarVisibility(true);
					}
				});
			}
		}

		ArrayList<Event> events = new ArrayList<Event>();
		Event[] eventsArr = null;
		Runnable updateList = new Runnable() {
			@Override
			public void run() {

				// Log.i("service2", " updating list");
				// TODO Auto-generated method stub

				eventListAdapter.setData(eventsArr);
				eventListAdapter.notifyDataSetChanged();
				setProgressBarIndeterminate(true);
				// eventListAdapter.notifyDataSetInvalidated();
			}
		};

		Runnable updateProgress = new Runnable() {
			public void run() {
				setTitle("Search results - found: " + totalFound);
				setProgressBarVisibility(false);
				setProgressBarVisibility(true);

			}
		};

		@Override
		public void run() {
			this.isRunning = true;

			boolean keepFetching = true;
			uws.setMethod(UpcomingWebService.Method.EVENT_SEARCH);
			uws.setParameters(this.searchParams);

			int perPage = 10;
			int maxResults = 100;
			totalFound = 0;

			uws.page = 1;
			uws.perPage = perPage;

			// set progress bar type
			if (isRunning) { // safety check when user quits the activity
								// while search is still going
				// we check on isRunning because user can quit the activity and
				// if the thread is changing the UI then we will crash.
				runOnUIThread(new Runnable() {
					public void run() {
						setProgressBarIndeterminate(true);
					}
				});
			}

			ProgressBar pb;

			while (keepFetching && isRunning) {

				if (!isPaused) {
					int numAdded = uws.get(events);
					totalFound += numAdded;

					if (numAdded == 0 || numAdded < perPage){ 
						keepFetching = false;
						
						// Update the info on status bar
						// we check on isRunning because user can quit the
						// activity and if the thread is changing the UI then we
						// will crash.
						if (!isPaused && isRunning) {
							runOnUIThread(updateProgress);
							runOnUIThread(updateList);
							runOnUIThread(new Runnable() {
								public void run() {
									setProgressBarVisibility(false);
								}
							});
						}
						break;
					}

					
					// we assume there's more when #results returned in 1 page == max per page
					else if (numAdded == perPage) {
						uws.page = uws.page + 1;
						Event[] contents = new Event[1];
						eventsArr = events.toArray(contents);

						if (!isPaused) {
							runOnUIThread(updateProgress);
							runOnUIThread(updateList);
						}
					} 

					// if the total found equal or exceeds maxResults then stop searching
					if (totalFound >= maxResults) {
						if (isRunning) { // safety check when user quits the
											// activity while search is still
											// going
							// hide progress bar
							runOnUIThread(new Runnable() {
								public void run() {
									setProgressBarVisibility(false);
								}
							});
						}
						isRunning = false;
						keepFetching = false;
					}
				}
			}
		}
	}
}
